package com.dinian.zeus.controller;

import com.dinian.zeus.util.Result;
import com.dinian.zeus.service.NewspaperService;
import com.dinian.zeus.service.PeriodicalService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


/**
 * @Author dinian
 * @Date 2019-01-02
 */
@Slf4j
@RestController
public class ExcelController {

    @Autowired
    private NewspaperService newspaperService;

    @Autowired
    private PeriodicalService periodicalService;

    /**
     *上传excel
     * @param file
     * @return
     */
    @RequestMapping("/uploadExcel")
    public Result upload(@RequestParam("file") MultipartFile file) throws Exception{
        String filename = file.getOriginalFilename();
        Integer importNum;
        if (filename.contains("报纸")){
            importNum = newspaperService.importNewspaper(file);
        }else if (filename.contains("期刊")){
            importNum = periodicalService.importPeriodical(file);
        }else {
            throw new Exception("文件命名不规范：未包含<期刊>或<报纸>");
        }
        if (importNum == 0){
            log.info("upload rowNum: {}",importNum);
            return Result.error("上传失败：Excel列可能不匹配");
        }else {
            log.info("upload rowNum: {}",importNum);
            return Result.ok("上传成功共"+importNum+"条");
        }
    }
}
